package com.example.server.intercept;


import com.example.server.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class LoginInterceptor implements HandlerInterceptor {


    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 添加 CORS 头部
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");

        // 如果是预检请求，则直接返回成功状态
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return false; // 不继续执行后续的拦截器或处理器
        }

        String token = request.getHeader("jwttoken");

        String tokenInRedis = redisTemplate.opsForValue().get(token);
        if(tokenInRedis == null) {
            throw new RuntimeException("token无效");
        }

        try{
            JWTUtils.validateToken(token);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("token无效");
        }

        return true;
    }
}
